﻿#include "ComputeLevels.h"
#include <gdal_priv.h>
using namespace rxtiler;
ComputeLevels::ComputeLevels()
{

}

bool ComputeLevels::computeLevels(rxtiler::TileOption *op, QString file, int &min, int &max)
{
    GDALDataset* poDataset = ( GDALDataset* )GDALOpen( file.toStdString().c_str(), GA_ReadOnly );
    if(!poDataset) return false;
    double adfGeoTransform[6];
    CPLErr res = poDataset->GetGeoTransform(adfGeoTransform);
    if(res != CE_None) {
        GDALClose(poDataset);
        return false;
    }

    int x=poDataset->GetRasterXSize();
    int y=poDataset->GetRasterYSize();

    double left=adfGeoTransform[0];
    //double top=adfGeoTransform[3];
    double right=adfGeoTransform[0]+x*adfGeoTransform[1]+y*adfGeoTransform[2];
    //double bottom=adfGeoTransform[3]+x*adfGeoTransform[4]+y*adfGeoTransform[5];

    double resx = (right-left)/x;

    int maxlevel = 0;
    for(int i=TileOption::MinLevel;i < TileOption::MaxLevel;i++){
        double r = op->getReslutionX(i);
        if(r <= resx){
            maxlevel = i-1;
            break;
        }
    }

    int minlevel= 0;
    for(int i=TileOption::MinLevel + 1;i < TileOption::MaxLevel;i++){
        double r = op->getTileWidth(i);
        if(r <= (right - left)){
            minlevel = i-1;
            break;
        }
    }
    if(maxlevel < minlevel){
        maxlevel = minlevel;
    }
    min = minlevel;
    max = maxlevel;

    GDALClose(poDataset);
    return true;
}


